//
//  LoginViewControler.m
//  jtpayTransactionInquiries
//
//  Created by dyj on 16/3/31.
//  Copyright © 2016年 Tangshan Jun-ho Technology Co.Ltd. All rights reserved.
//
#import "LoginViewControler.h"
#import "AppDelegate.h"
#import "SSKeychain.h"
#import <ReactiveCocoa/ReactiveCocoa.h>
#import "AFNHTTPSessionManager.h"
#import "HLMBProgressHUD.h"
#import "ZZAESTool.h"
#import "ConfigureHeader.h"
#import "ViewController.h"
#import "MD5.h"
#import "MYRequest.h"
#import <JPush/JPUSHService.h>
@class AppDelegate;
@interface LoginViewControler()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *headerImageView;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *passWord;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
//@property (copy,nonatomic) NSArray *array;

@end
@implementation LoginViewControler

- (void)viewDidLoad{
    [super viewDidLoad];
    NSLog(@"%f",[UIScreen mainScreen].scale);
    self.userName.delegate=self;
    self.passWord.delegate=self;
    UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    UIImageView *img1=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];

    img.image=[UIImage imageNamed:@"tj-yx.png"];
    img1.image=[UIImage imageNamed:@"tj-mm.png"];

    self.userName.leftViewMode = UITextFieldViewModeAlways;
    self.passWord.leftViewMode = UITextFieldViewModeAlways;
    self.userName.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.userName.layer.borderWidth = 1.5f;
    self.userName.layer.cornerRadius = 8.0;
    [self.userName setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

    self.passWord.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.passWord.layer.borderWidth = 1.5f;
    self.passWord.layer.cornerRadius = 8.0;
    [self.passWord setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

    [self.userName setLeftView:img];
    [self.passWord setLeftView:img1];

    
//           NSLog(@"===%@===%@====%ld===",[[SSKeychain allAccounts]lastObject][@"acct"],[SSKeychain passwordForService:@"com.JunHao.Merchant" account:[[SSKeychain allAccounts]lastObject][@"acct"] error:nil],[SSKeychain allAccounts].count);
    self.userName.text = [[SSKeychain allAccounts]lastObject][@"acct"];
    self.passWord.text = [SSKeychain passwordForService:USER_NAME account:[[SSKeychain allAccounts]lastObject][@"acct"] error:nil];

   RACSignal *userNameSignal=[self.userName.rac_textSignal map:^id(NSString * value) {
    
    return @([self isValidUsername:value]);
}];
    RACSignal *passWordSignal=[self.passWord.rac_textSignal map:^id(NSString * value) {
        
        return @([self isValidPassWord:value]);
    }];
    RACSignal *signUpActiveSignal =
    [RACSignal combineLatest:@[userNameSignal, passWordSignal]
                      reduce: ^id(NSNumber *usernameValid, NSNumber *passwordValid){
                          return @([usernameValid boolValue]&&[passwordValid boolValue]);
                      }];

    [signUpActiveSignal subscribeNext:^(NSNumber*signupActive){
        self.loginButton.enabled =[signupActive boolValue];
    }];
    
    [[self.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(UIButton *button) {
            [self loginButtonAction];

        
    } completed:^{

    }];
    
    [[SSKeychain allAccounts]lastObject];
 

}
//- (void)registerSuccessedNotice:(NSDictionary*)tokenDic{
//    //注册通知
//    NSNotification *notification = [NSNotification notificationWithName:@"loginSuccessed" object:nil userInfo:tokenDic];
//    [[NSNotificationCenter defaultCenter]postNotification:notification];
//    
//}
- (void)deleteAllacountsWithService:(NSString *)serviceName{
    NSArray*accounts = [SSKeychain accountsForService:serviceName];
    for (NSDictionary*dic in accounts) {
        SSKeychainQuery *query=[[SSKeychainQuery alloc]init];
        query.service =serviceName;
        query.account =[dic valueForKey:@"acct"];
        [query deleteItem:nil];

    }
    NSLog(@"%@",[SSKeychain accountsForService:serviceName]);
}
- (BOOL)isValidUsername:(NSString *)text{

    if (ABS(text.length)==0) {
        return NO;
    }else{
        return YES;
    }


}
- (BOOL)isValidPassWord:(NSString *)text{
    if (ABS(text.length)==0){
        return NO;
    }else{
        return YES;
    }
}
- (void)loginButtonAction{
    
    [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:@"loading"];
    ZZAESTool *zz=[[ZZAESTool alloc]init];
    NSString *md5Str = [MD5 md532BitLower:self.passWord.text];
   NSString *aesPassword=[zz AESencodeWithDic:md5Str];
    NSString *registrationID =[JPUSHService registrationID]?[JPUSHService registrationID]:@"1121312312";
    NSString *sign = [MD5 md532BitLower:[NSString stringWithFormat:@"%@&%@&%@",self.userName.text,md5Str,registrationID]];
    [MYRequest postWithUrl:API_LOGIN pamaterdic:@{@"Phone_No":self.userName.text,@"User_Password":aesPassword,@"Device_Code":registrationID,@"sign":sign} resultBlock:^(id result) {
        if ([result[@"Flag"] boolValue]) {
            [self deleteAllacountsWithService:USER_NAME];
              [SSKeychain setPassword:self.passWord.text forService:USER_NAME account:self.userName.text];
            id<UIApplicationDelegate> app2 = [UIApplication sharedApplication].delegate;
            UIStoryboard *board =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            ViewController *vc = [board instantiateInitialViewController];
              NSDictionary *msgDic = [NSJSONSerialization JSONObjectWithData:[result[@"Msg"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            vc.userName = msgDic[@"User_Name"];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
            app2.window.rootViewController = nav;
          
            NSLog(@"%@",msgDic);
        }else{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [HLMBProgressHUD addMBProgressHUDinView:self.view hudMode:MBProgressHUDModeText hideDelay:1.5 hudDetailText:result[@"Msg"]];
        }
    } errorBlock:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [HLMBProgressHUD addMBProgressHUDinView:self.view hudMode:MBProgressHUDModeText hideDelay:1.5 hudDetailText:@"登陆失败"];
    }];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.userName) {
        [self.passWord becomeFirstResponder];
        return NO;
    }else{
        if (self.loginButton.enabled) {
            [self loginButtonAction];

        }
    }
    return YES;
}

@end
